﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;

namespace CommonUtils
{
    /// <summary>
    /// https://blog.csdn.net/fromfire2/article/details/102605174
    /// </summary>
    public static class SwaggerUtil
    {
        public static void AddMySwagger(this IServiceCollection services)
        {
            services.AddRazorPages();

            services.AddControllers()
            //原生Json服务中文、变量、注释支持差，这里切换为Newtonsoft提供的Json服务，必须引用Microsoft.AspNetCore.Mvc.NewtonsoftJson，引用Newtonsoft.Json此处无效
            .AddNewtonsoftJson(options =>
            {
                //保持Json属性/变量大小写
                options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                //如字段为null值，该字段不会返回到前端
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            });

            //生成swagger
            services.AddSwaggerGen(options =>
            {
                //设置swagger标题
                options.SwaggerDoc("doc", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "@Title", Version = "v1.0" });
                //添加接口注释
                options.IncludeXmlComments("comment.xml");
            });
        }

        public static void UseMySwagger(this IApplicationBuilder app)
        {
            app.UseStaticFiles();
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
            });
            app.UseSwagger();
            app.UseSwaggerUI(options => options.SwaggerEndpoint("/swagger/doc/swagger.json", null));
        }
    }
}
